import { request } from '@umijs/max';

// 项目相关的API接口
export interface Project {
  id: string;
  name: string;
  description: string;
  status: 'active' | 'inactive' | 'archived';
  api_key: string;
  owner: string;
  created_at: string;
  updated_at: string;
  error_count?: number;
  recent_errors?: any[];
  last_error_time?: string;
}

export interface ProjectCreateParams {
  name: string;
  description: string;
  status?: 'active' | 'inactive';
}

export interface ProjectUpdateParams {
  name?: string;
  description?: string;
  status?: 'active' | 'inactive' | 'archived';
}

export interface ProjectResponse {
  success: boolean;
  message?: string;
  data?: Project;
  errors?: any;
}

export interface ProjectListResponse {
  success: boolean;
  message?: string;
  data?: {
    results: Project[];
    count: number;
    next?: string;
    previous?: string;
  };
  errors?: any;
}

// 获取项目列表
export async function getProjects(params?: {
  page?: number;
  page_size?: number;
  search?: string;
  status?: string;
}) {
  return request<ProjectListResponse>('/api/projects/', {
    method: 'GET',
    params,
  });
}

// 创建项目
export async function createProject(params: ProjectCreateParams) {
  return request<ProjectResponse>('/api/projects/', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    data: params,
  });
}

// 获取项目详情
export async function getProject(id: string) {
  return request<ProjectResponse>(`/api/projects/${id}/`, {
    method: 'GET',
  });
}

// 更新项目
export async function updateProject(id: string, params: ProjectUpdateParams) {
  return request<ProjectResponse>(`/api/projects/${id}/`, {
    method: 'PATCH',
    headers: {
      'Content-Type': 'application/json',
    },
    data: params,
  });
}

// 删除项目
export async function deleteProject(id: string) {
  return request(`/api/projects/${id}/`, {
    method: 'DELETE',
  });
}

// 重新生成API密钥
export async function regenerateApiKey(id: string) {
  return request<ProjectResponse>(`/api/projects/${id}/regenerate_api_key/`, {
    method: 'POST',
  });
}

// 获取项目API密钥
export async function getProjectApiKey(id: string) {
  return request<{ api_key: string }>(`/api/projects/${id}/api_key/`, {
    method: 'GET',
  });
}


// 统一API响应格式
export interface ApiResponse<T = any> {
  success: boolean;
  code: number;
  data?: T;
  message: string;
}

export interface PaginatedData<T> {
  results: T[];
  count: number;
  next?: string;
  previous?: string;
}

// 错误码枚举
export enum ErrorCode {
  SUCCESS = 0,
  GENERAL_ERROR = -1,
  VALIDATION_ERROR = 1001,
  AUTHENTICATION_ERROR = 1101,
  PERMISSION_ERROR = 1102,
  NOT_FOUND_ERROR = 1201,
  DATABASE_ERROR = 1301,
  PROJECT_NAME_EXISTS = 2001,
}